﻿using HsServerHa.Core.Http;
using HsServerHa.Entity;
using HsServerHa.Entity.Models;
using HsServerHa.Entity.Models.SqlserverMirror;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HsServerHa.Utility.SqlserverMirror
{
    public class DeleteMirrorCommand : OperateCommandBase
    {
        public DeleteMirrorCommand()
        {
            Operate = "删除镜像";
            OperateCommand = OperateCommand.Begin;
        }

        public override async Task<OperateCommand> operate(ObservableCollection<string> LogTextBox, string path, bool isAutoCopy)
        {
            if (!CheckStatementCommand.DeletePartner(LogTextBox, MainSqlConnectString, DataBaseName, MainServer))
            {
                OperateCommand = OperateCommand.Begin;
                throw new Exception("断开伙伴关系失败！");
            }
            else
            {
                OperateCommand = OperateCommand.DeleteMainPartner;
            }

            if (!CheckStatementCommand.DeletePartner(LogTextBox, SlaveSqlConnectString, DataBaseName, SlaveServer))
            {
                OperateCommand = OperateCommand.Begin;
                throw new Exception("断开伙伴关系失败！");
            }
            else
            {
                OperateCommand = OperateCommand.Compelete;
            }

            SQLiteHelper.ExecuteSql($"delete from SQLManage where DBName='{DataBaseName}' ");

            //删除远程镜像数据
            var parms = new SQLManageEntity
            {
                DBName = DataBaseName
            };
            var slaveServer = SlaveServer;
            var masterSlaveBindEntity = SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().Result.FirstOrDefault();
            if (masterSlaveBindEntity != null)
            {
                slaveServer = masterSlaveBindEntity.SlaveIP;
            }
            var slavePath = $"http://{slaveServer}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
            var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
           (ConfigurationManager.AppSettings["postSqlManageDeleteByDBName"]?.ToString() ?? "postSqlManageDeleteByDBName"), JsonConvert.SerializeObject(parms)).Result;

            //删除备份文件
            DbBackFilePathEntity dbBackFilePathEntity = SQLiteHelper.Table<DbBackFilePathEntity>().FirstOrDefault();
            var dbBackFiles = new List<string>();
            if (dbBackFilePathEntity != null)
            {
                dbBackFiles.Add($"{dbBackFilePathEntity.FilePath}\\{DataBaseName}.bak");
                dbBackFiles.Add($"{dbBackFilePathEntity.FilePath}\\{DataBaseName}_log.bak");
            }
            foreach (string file in dbBackFiles)
            {
                File.Delete(file);
            }

            //删除从机备份文件
            var databaseServerEntity = SQLiteHelper.Table<DatabaseServerEntity>().FirstOrDefault(x => x.ServerType == "Slave");
            var dbHelperSQL = new DbHelperSQL(databaseServerEntity.DbConnectStr);
            var deleteDatabaseEntity = CheckStatementCommand.CheckStatementsEntities.FirstOrDefault(x => x.type == "deletedatabase");
            if (deleteDatabaseEntity != null)
            {
                dbHelperSQL.ExecuteSql(deleteDatabaseEntity.Statement.Replace("DataBaseName", DataBaseName));
            }



            return OperateCommand;
        }
    }
}
